package com.thd.framework.codegenerator.core.tableutil;


import com.thd.framework.codegenerator.core.dbtype.DbType;
import com.thd.framework.codegenerator.core.dto.Table;
import com.thd.framework.codegenerator.core.dto.TemplateData;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;


@Data
public abstract class TableUtilImpl implements TableUtil {
	protected String schema;
	@Autowired
	private TemplateData templateData;
	@Autowired
	private JdbcTemplate jdbcTemplate;

	//数据库类型 oracle mysql sqlserver
	protected DbType dbtype;


	public Logger log = LoggerFactory.getLogger(this.getClass());
	
	protected Map<String,String> dataTypeMap = new HashMap<String,String>();
	
//	protected TableUtilImpl(DbType dbType,String schema,JdbcTemplate jdbcTemplate,TemplateData templateData){
//		this.dbtype = dbType;
//		this.schema = schema;
//		this.jdbcTemplate = jdbcTemplate;
//		this.templateData = templateData;
//	}

	@PostConstruct
	public void initExtraColumnTypeMapping(){
		addExtralColumnTypeMapping();
		this.schema = this.templateData.getSchema();
		this.dbtype = DbType.valueOf(this.templateData.getDbType().toUpperCase());

	}


	/**
	 * 加载自定义的数据类型映射
	 */
	protected void addExtralColumnTypeMapping(){
		System.out.println("============ 加载自定义字段类型 =============");
		Map<String,String> extraColumnType = this.getTemplateData().getCustomData().getExtraColumnTypeMapping();
		if(null != extraColumnType){
			Set<Map.Entry<String,String>> entry = extraColumnType.entrySet();
			if(entry.size() > 0){
				Iterator<Map.Entry<String,String>> iter = entry.iterator();
				while(iter.hasNext()){
					Map.Entry<String,String> dataTypeMapItem = iter.next();
					this.dataTypeMap.put(dataTypeMapItem.getKey(),dataTypeMapItem.getValue());
				}
			}
		}

	}



	public abstract Table loadTable(String dbTableName) throws Exception;





}
